package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.mapper.CourseMapper;
import com.demo.mapper.StudentCourseMapper;
import com.demo.mapper.StudentMapper;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.pojo.entity.Course;
import com.demo.pojo.entity.Student;
import com.demo.pojo.entity.StudentCourse;
import com.demo.service.StudentUserService;
import com.demo.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 学生用户服务实现类
 */
@Service
public class StudentUserServiceImpl implements StudentUserService {
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private StudentCourseMapper studentCourseMapper;
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private ScheduleService scheduleService;
    
    @Override
    public Student studentLogin(Long stuNo, String password) {
        if (stuNo == null) {
            throw new RuntimeException("学号不能为空");
        }
        
        if (password == null || password.trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no", stuNo);
        Student student = studentMapper.selectOne(queryWrapper);
        
        if (student == null) {
            throw new RuntimeException("学号不存在");
        }
        
        // 验证身份证后六位
        String idCard = student.getStuIdCard();
        if (idCard == null || idCard.length() < 6) {
            throw new RuntimeException("学生身份证信息不完整");
        }
        
        String lastSixDigits = idCard.substring(idCard.length() - 6);
        if (!password.equals(lastSixDigits)) {
            throw new RuntimeException("密码错误，请输入身份证后六位");
        }
        
        return student;
    }
    
    @Override
    public Student getStudentInfo(Long studentId) {
        return studentMapper.selectById(studentId);
    }
    
    @Override
    public boolean updateStudentInfo(Student student) {
        return studentMapper.updateById(student) > 0;
    }
    
    @Override
    public List<ScheduleListDTO> getStudentSchedule(Long studentId, String semester) {
        // 按学生所属班级获取课表；带学期兜底
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            return new ArrayList<>();
        }
        Long clazzId = student.getClazzId();
        if (clazzId == null) {
            return new ArrayList<>();
        }
        String usedSemester = (semester == null || semester.isBlank()) ? "advanced" : semester;
        List<ScheduleListDTO> list = scheduleService.getClassSchedule(clazzId, usedSemester);
        if ((list == null || list.isEmpty()) && !"2025-1".equals(usedSemester)) {
            list = scheduleService.getClassSchedule(clazzId, "2025-1");
        }
        return list == null ? new ArrayList<>() : list;
    }
    
    @Override
    public List<ScheduleListDTO> getStudentWeekSchedule(Long studentId, String semester, Integer weekNo) {
        List<ScheduleListDTO> allSchedules = getStudentSchedule(studentId, semester);
        // 简化实现，实际需要根据周次过滤
        return allSchedules;
    }
    
    @Override
    public List<ScheduleListDTO> getStudentTodaySchedule(Long studentId, String semester, Integer weekNo, Integer dayOfWeek) {
        List<ScheduleListDTO> allSchedules = getStudentSchedule(studentId, semester);
        // 简化实现，实际需要根据星期几过滤
        return allSchedules;
    }
    
    @Override
    public List<Map<String, Object>> getAvailableCourses(Long studentId, String semester) {
        // 获取可选课程列表
        List<Course> courses = courseMapper.selectList(null);
        
        List<Map<String, Object>> availableCourses = new ArrayList<>();
        for (Course course : courses) {
            Map<String, Object> courseInfo = new HashMap<>();
            courseInfo.put("courseId", course.getCourseId());
            courseInfo.put("courseName", course.getCourseName());
            courseInfo.put("courseType", course.getCourseType());
            courseInfo.put("credit", course.getCredit());
            courseInfo.put("periodTotal", course.getPeriodTotal());
            courseInfo.put("dept", course.getDept());
            availableCourses.add(courseInfo);
        }
        
        return availableCourses;
    }
    
    @Override
    public boolean selectCourse(Long studentId, Long courseId) {
        try {
            // 检查是否已选课
            QueryWrapper<StudentCourse> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("student_id", studentId)
                       .eq("course_id", courseId)
                       .eq("status", "SELECTED");
            StudentCourse existing = studentCourseMapper.selectOne(checkWrapper);
            
            if (existing != null) {
                return false; // 已选课
            }
            
            // 创建选课记录
            StudentCourse studentCourse = new StudentCourse();
            studentCourse.setStudentId(studentId);
            studentCourse.setCourseId(courseId);
            studentCourse.setSemester("2024-1"); // 简化处理
            studentCourse.setStatus("SELECTED");
            studentCourse.setSelectTime(new Date());
            studentCourse.setCreateTime(new Date());
            studentCourse.setUpdateTime(new Date());
            
            return studentCourseMapper.insert(studentCourse) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public boolean dropCourse(Long studentId, Long courseId) {
        try {
            QueryWrapper<StudentCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId)
                   .eq("course_id", courseId)
                   .eq("status", "SELECTED");
            
            StudentCourse studentCourse = studentCourseMapper.selectOne(wrapper);
            if (studentCourse != null) {
                studentCourse.setStatus("DROPPED");
                studentCourse.setDropTime(new Date());
                studentCourse.setUpdateTime(new Date());
                return studentCourseMapper.updateById(studentCourse) > 0;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getSelectedCourses(Long studentId, String semester) {
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                   .eq("semester", semester)
                   .eq("status", "SELECTED");
        
        List<StudentCourse> studentCourses = studentCourseMapper.selectList(queryWrapper);
        
        List<Map<String, Object>> selectedCourses = new ArrayList<>();
        for (StudentCourse sc : studentCourses) {
            Course course = courseMapper.selectById(sc.getCourseId());
            if (course != null) {
                Map<String, Object> courseInfo = new HashMap<>();
                courseInfo.put("studentCourseId", sc.getId());
                courseInfo.put("courseId", course.getCourseId());
                courseInfo.put("courseName", course.getCourseName());
                courseInfo.put("courseType", course.getCourseType());
                courseInfo.put("credit", course.getCredit());
                courseInfo.put("selectTime", sc.getSelectTime());
                selectedCourses.add(courseInfo);
            }
        }
        
        return selectedCourses;
    }
    
    @Override
    public List<Map<String, Object>> getStudentGrades(Long studentId, String semester) {
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                   .eq("semester", semester)
                   .in("status", Arrays.asList("COMPLETED", "SELECTED"));
        
        List<StudentCourse> studentCourses = studentCourseMapper.selectList(queryWrapper);
        
        List<Map<String, Object>> grades = new ArrayList<>();
        for (StudentCourse sc : studentCourses) {
            Course course = courseMapper.selectById(sc.getCourseId());
            if (course != null) {
                Map<String, Object> gradeInfo = new HashMap<>();
                gradeInfo.put("courseName", course.getCourseName());
                gradeInfo.put("credit", course.getCredit());
                gradeInfo.put("grade", sc.getGrade());
                gradeInfo.put("status", sc.getStatus());
                grades.add(gradeInfo);
            }
        }
        
        return grades;
    }
    
    @Override
    public Map<String, Object> getStudentCreditStats(Long studentId) {
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                   .eq("status", "COMPLETED");
        
        List<StudentCourse> completedCourses = studentCourseMapper.selectList(queryWrapper);
        
        BigDecimal totalCredits = BigDecimal.ZERO;
        for (StudentCourse sc : completedCourses) {
            if (sc.getCredit() != null) {
                totalCredits = totalCredits.add(sc.getCredit());
            }
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCredits", totalCredits);
        stats.put("completedCourses", completedCourses.size());
        
        return stats;
    }
}
